import { Component, OnInit } from '@angular/core';
import { BroadcastService } from 'src/app/services/broadcast.service';
import { dataBody, field } from 'src/utils/dataType';
import { exportPdf } from 'src/utils/utils';
import * as XLSX from 'xlsx';
import { MateDataService } from 'src/app/services/mate_data.service';
import { SessionService } from 'src/app/services/session.service';


@Component({
    selector: 'app-tool-bar',
    templateUrl: './tool-bar.component.html',
    styleUrls: ['./tool-bar.component.scss']
})
export class ToolBarComponent implements OnInit {

    public element: any;
    msgs: Array<Object> = [];
    // bodyData:dataBody;
    constructor(
        private broadcastService: BroadcastService,
        private sessionSvc:SessionService
        ) { }
    ngOnInit(): void {

    }

    inportData(evt) {
        
        const userInfo = this.sessionSvc.getSessionValue('user');

        const ExcelBodyData: dataBody = {
            name: '',
            label: '',
            orgId: userInfo.userId,
            objId: 'B00001',
            createBy: userInfo.userName,
            lastModifiedBy: userInfo.userName,
            ownerId: userInfo.userId,
            fieldList: [],
            dataList: []
        };
        const broadcast = this.broadcastService;
        const target: DataTransfer = <DataTransfer>(evt.target);
        if (target.files.length !== 1) {
            this.msgs = [
                { severity: 'Error', summary: '失败', content: '只能导入1个文件！' },
            ]
        }
        ExcelBodyData.name = target.files[0].name;
        ExcelBodyData.label = target.files[0].name;
        const reader: FileReader = new FileReader();
        reader.onload = (e: any) => {
            try {
                const data = e.target.result
                var workbook = XLSX.read(data, {
                    type: 'binary'
                }) // 以二进制流方式读取得到整份excel表格对象

                var persons = []; // 存储获取到的数据

            } catch (e) {
                console.log('文件类型不正确');
                return;
            }
            // 表格的表格范围，可用于判断表头是否数量是否正确
            var fromTo = '';
            // const sheetnames: any = [];
            // 遍历每张表读取
            for (let sheet in workbook.Sheets) {
                if (workbook.Sheets.hasOwnProperty(sheet)) {
                    fromTo = workbook.Sheets[sheet]['!ref'] || '';

                    // 获取有效值
                    persons = persons.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
                    const range = XLSX.utils.decode_range(fromTo);

                    ExcelBodyData.fieldList = this.getHeader(workbook.Sheets[sheet], range);

                    // 通过工作表的所有有效行列，将空行和空值补全，
                    // 最终获得有效范围内的所有单元格数据

                    //记录连续空行
                    let blankRow:any = [];

                    for (let i = range.s.r+1; i <= range.e.r; i++) {
                        let temp = persons.filter((item: any) => item.__rowNum__ == i) || null;
                        let info: any = {};
                        let key = '';
                        // 对应行有值则用对应行的有效值值
                        if (temp.length > 0) {
                            for (let j = 0; j < ExcelBodyData.fieldList.length; j++) {
                                key = ExcelBodyData.fieldList[j].label;
                                info[key] = temp[0][key] ? temp[0][key] : '';
                            }
                            info["row"] = temp[0]['__rowNum__'];
                            ExcelBodyData.dataList.push(info);
                            ExcelBodyData.dataList = [...ExcelBodyData.dataList, ...blankRow];
                            blankRow = [];
                        } else {
                            // 对应行无值，则用空字符串补全
                            for (let j = 0; j < ExcelBodyData.fieldList.length; j++) {
                                key = ExcelBodyData.fieldList[j].label;
                                info[key] = '';
                            }
                            info["row"] = i;
                            blankRow.push(info);
                        }
                    }
                    break; // 如果只取第一张表，就取消注释这行,循环取就加上注释
                }
            }
            broadcast.broadcast('refreshTableData_import', ExcelBodyData);
        };
        reader.readAsBinaryString(target.files[0]);
        // 为了上传触发onChange，需要将上传input的value手动改成空，
        // 否则上传相同文件(内容改变)触发不了上传
        const dom:any = document.getElementById('inputFile') as HTMLElement;
        dom.value = "";
    }

    getHeader(sheet, range) {
        const headers: any = [];
        /* 获取单元格值 start in the first row */
        const R = range.s.r; // 行 // C 列
        let i = 0;
        for (let C = range.s.c; C <= range.e.c; ++C) {
            /* 根据地址得到单元格的值find the cell in the first row */
            let cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })];
            // 如果有空表头，会替换为您想要的默认值replace with your desired default
            var hdr = "UNKNOWN" + C;
            // XLSX.utils.format_cell 生成单元格文本值
            if (cell && cell.t) {
                hdr = XLSX.utils.format_cell(cell);
            }
            if (hdr.indexOf('UNKNOWN') > -1) {
                if (!i) {
                    hdr = '__EMPTY';
                } else {
                    hdr = '__EMPTY_' + i;
                }
                i++;
            }
            headers.push({
                fieldId: '',
                label: hdr,
                fieldNum: C + 1
            });
        }
        return headers;
    }


    export(domId: string, title?) {
        const element = document.getElementById(domId) as HTMLElement;
        exportPdf(element, title);
    }
}
